package com.wangp.mywrite.s_netty.netty.ch2;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @description: TODO
 * @author tooStronger
 * @date 2023/3/17
 */
@Slf4j
public class EventLoopClient {

    public static void main(String[] args) throws InterruptedException {
        // 1. 创建启动器类
        ChannelFuture channelFuture = new Bootstrap()
                // 2. 添加eventLoop
                .group(new NioEventLoopGroup())
                // 3. 客户端channel实现
                .channel(NioSocketChannel.class)
                // 4. 添加处理器
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    // 建立连接后调用
                    @Override
                    protected void initChannel(NioSocketChannel nsc) throws Exception {
                        nsc.pipeline().addLast(new StringEncoder());
                    }
                })
                // 5.连接到服务器，connect 是异步非阻塞的,main线程发起，真正执行connect是nio线程
                .connect(new InetSocketAddress("localhost", 8080));
        // 阻塞直到连接建立,不写 sync main线程会无阻塞向下执行，会导致main线程先执行以下代码
        // 那么如何获取 channelFuture 的结果？
        // 1- sync 方法同步，sync 可以阻塞当前线程，直到nio线程连接完毕
//        channelFuture.sync();
//        Channel channel = channelFuture.channel();
//        channel.writeAndFlush("hello world");
//        log.info("{}",channel);
        // 2- addListener(回调对象) 异步处理结果
        channelFuture.addListener(new ChannelFutureListener() {
            // nio 线程连接建立好后，会调用
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                Channel channel = future.channel();
                channel.writeAndFlush("hello world");
                log.info("{}",channel);
            }
        });

        System.out.println();
    }
}
